package com.training.project.util;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.training.project.entity.Pet;

public class XmlHelper {
	private static Document doc;
	private static Element root;
	private static final String FILE_PATH = "E:\\JavaWork\\java-io\\src\\com\\training\\project\\resources\\pets.xml";

	static {
		init();
	}

	private static void init() {
		try {
			doc = new SAXReader().read(new FileReader(FILE_PATH));
			root = doc.getRootElement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static List<Pet> readFromXml() {
		List<Pet> list = new ArrayList<>();
		List<Element> elements = root.elements();
		for (Element element : elements) {
			int id = Integer.parseInt(element.attributeValue("id"));
			int age = Integer.parseInt(element.attributeValue("age"));
			String category = element.attributeValue("category");
			String kind = element.attributeValue("kind");
			String gender = element.attributeValue("gender");
			double weight = Double.parseDouble(element.attributeValue("weight"));
			double price = Double.parseDouble(element.attributeValue("price"));

			Pet pet = new Pet(category, kind, gender, age, weight, price);
			pet.setId(id);
			list.add(pet);
		}
		System.out.println("读取宠物信息成功...");
		return list;
	}

	public static void saveToXml(Pet pet) {
		Element element = root.addElement("pet");
		element.addAttribute("id", pet.getId() + "");
		element.addAttribute("category", pet.getCategory());
		element.addAttribute("kind", pet.getKind());
		element.addAttribute("gender", pet.getGender());
		element.addAttribute("age", pet.getAge() + "");
		element.addAttribute("weight", pet.getWeight() + "");
		element.addAttribute("price", pet.getPrice() + "");
		OutputFormat format = OutputFormat.createCompactFormat();
		format.setEncoding("utf-8");
		XMLWriter out = null;
		try {
			out = new XMLWriter(new FileWriter(FILE_PATH), format);
			out.write(doc);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
